package com.wang.madness.interceptor;

import com.alibaba.fastjson.JSON;
import com.wang.madness.annotation.PassToken;
import com.wang.madness.customEnum.ErrorShowType;
import com.wang.madness.customEnum.ResultCode;
import com.wang.madness.customResponse.ErrorResult;
import com.wang.madness.utils.JwtUtil;
import java.io.IOException;
import java.lang.reflect.Method;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * 自定义JWT拦截器
 * +
 * @author 王文君
 */
@Slf4j
@Component
public class JwtAuthenticationInterceptor implements HandlerInterceptor {

  private final JwtUtil jwtUtil;

  @Autowired
  public JwtAuthenticationInterceptor(JwtUtil jwtUtil) {
    this.jwtUtil = jwtUtil;
  }

  @Override
  public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
      throws IOException {
    log.info("请求地址=======>" + request.getRequestURI());
    String token = request.getHeader("token");
    if (!(handler instanceof HandlerMethod)) {
      return true;
    }
    HandlerMethod handlerMethod = (HandlerMethod) handler;
    Method method = handlerMethod.getMethod();
    if (method.isAnnotationPresent(PassToken.class)) {
      log.info("此接口无需请求令牌");
      PassToken passToken = method.getAnnotation(PassToken.class);
      return passToken.required();
    } else {
      response.setHeader("Content-Type", "application/json;charset=UTF-8");
      log.info("登录令牌=======>" + token);
      if (token == null) {
        log.warn("请求无登录令牌");
        ErrorResult<String> errorResult = new ErrorResult<>(false, "未登录!", ResultCode.UNAUTHORIZED,
            ErrorShowType.NOTIFICATION, "127.0.0.1");
        response.setStatus(HttpStatus.FORBIDDEN.value());
        response.getWriter().write(JSON.toJSONString(errorResult));
        return false;
      }
      String userId = jwtUtil.getAudience(token);
      boolean useful = jwtUtil.verifyToken(token, userId);
      if (!useful) {
        ErrorResult<String> errorResult = new ErrorResult<>(false, "授权已过期!", ResultCode.UNAUTHORIZED,
            ErrorShowType.NOTIFICATION, "127.0.0.1");
        response.setStatus(HttpStatus.FORBIDDEN.value());
        response.getWriter().write(JSON.toJSONString(errorResult));
        return false;
      }
      return true;
    }
  }
}
